package com.lc.activiti.config;

import com.lc.activiti.sys.service.SysRoleService;
import com.lc.activiti.sys.service.SysUserService;
import com.lc.activiti.utils.RSAUtils;
import com.lc.activiti.utils.redis.RedisUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.security.KeyPair;
import java.util.Base64;

/**
 * 启动项目时执行
 * @Description:
 * @author: 骆超
 * @date: 2021/5/20 17:09
 */
@Component
@Slf4j
public class InitProjectBasics implements ApplicationRunner {

    @Resource
    SysUserService sysUserService;
    @Resource
    SysRoleService sysRoleService;

    @Override
    public void run(ApplicationArguments args) throws Exception {
        //第一步需要清理
        RedisUtil.clear();
        this.setKeyPair();
        sysUserService.setUserMap();
        sysRoleService.setRoleMap();
    }

    /**
     * 生成密钥对并塞入redis中
     * @author 骆超
     * @date 2021/6/18
     */
    private void setKeyPair() throws Exception {
        KeyPair keyPair = RSAUtils.getKeyPair();
        //生成公钥和私钥
        String privateKey = new String(Base64.getEncoder().encode(keyPair.getPrivate().getEncoded()));
        String publicKey = new String(Base64.getEncoder().encode(keyPair.getPublic().getEncoded()));
        //将公钥和私钥存入redis中
        RedisUtil.set(ConstantsPile.RSA_PRIVATE_KEY,privateKey);
        RedisUtil.set(ConstantsPile.RSA_PUBLIC_KEY,publicKey);
        log.info("私钥:" + privateKey);
        log.info("公钥:" + publicKey);
    }


}

